package com.renchunlin.taobaounion.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.renchunlin.taobaounion.R;
import com.renchunlin.taobaounion.base.BaseFragment;
import com.renchunlin.taobaounion.custom.AutoLoopViewPager;
import com.renchunlin.taobaounion.model.domain.Categories;
import com.renchunlin.taobaounion.model.domain.HomePagerContent;
import com.renchunlin.taobaounion.model.domain.IBaseInfo;
import com.renchunlin.taobaounion.model.domain.ILinaerItemInfo;
import com.renchunlin.taobaounion.presenter.ICategoryPagerPresenter;
import com.renchunlin.taobaounion.presenter.ITicketPresenter;
import com.renchunlin.taobaounion.ui.adapter.LinearItemContentAdapter;
import com.renchunlin.taobaounion.ui.adapter.LooperPagerAdapter;
import com.renchunlin.taobaounion.utils.PresenterManager;
import com.renchunlin.taobaounion.utils.SizeUtils;
import com.renchunlin.taobaounion.utils.TicketUtil;
import com.renchunlin.taobaounion.utils.ToastUtil;
import com.renchunlin.taobaounion.view.ICategoryPageCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static com.renchunlin.taobaounion.utils.Constants.KEY_HOME_PAGER_MATERIAL_ID;
import static com.renchunlin.taobaounion.utils.Constants.KEY_HOME_PAGER_TITLE;

public class HomePagerFragment extends BaseFragment implements ICategoryPageCallback {

    private ICategoryPagerPresenter mCategoryPagerPresenter;
    private int materialid;
    private LinearItemContentAdapter contentAdapter;
    private LooperPagerAdapter looperPagerAdapter;
    private View headerView;
    private List<ILinaerItemInfo> datas = new ArrayList<>();
    private ITicketPresenter mTicketPresenter;

    public static HomePagerFragment newInstance(Categories.DataBean categories) {
        HomePagerFragment homePagerFragment = new HomePagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_HOME_PAGER_TITLE, categories.getTitle());
        bundle.putInt(KEY_HOME_PAGER_MATERIAL_ID, categories.getId());
        homePagerFragment.setArguments(bundle);
        return homePagerFragment;
    }

    @BindView(R.id.home_pager_content_list)
    public RecyclerView mContentList;

    private AutoLoopViewPager looperPager;

    private TextView currentCategoryTitleTv;

    private LinearLayout looperPointContainer;

    @BindView(R.id.home_pager_refresh)
    public TwinklingRefreshLayout twinklingRefreshLayout;

    @BindView(R.id.cl_layout)
    public ConstraintLayout cl_layout;

    @Override
    protected int getRootViewResId() {
        return R.layout.fragment_home_pager;
    }

    @Override
    public void onResume() {
        super.onResume();
        //可见的时候去调用轮播
        looperPager.startLoop();
    }

    @Override
    public void onPause() {
        super.onPause();
        //不可见的时候暂停
        looperPager.stopLoop();
    }

    @Override
    protected void initListener() {

        cl_layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (cl_layout == null) {
                    return;
                }
                int measuredHeight = cl_layout.getMeasuredHeight();
                ViewGroup.LayoutParams layoutParams = mContentList.getLayoutParams();
                layoutParams.height = measuredHeight;
                mContentList.setLayoutParams(layoutParams);
                if (measuredHeight != 0) {
                    cl_layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });

        looperPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (looperPagerAdapter.getDataSize() == 0) {
                    return;
                }

                int targetPosition = position % looperPagerAdapter.getDataSize();
                //切换指示器
                updateLooperIndicator(targetPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                if (mCategoryPagerPresenter != null) {
                    mCategoryPagerPresenter.loadMore(materialid);
                }
            }
        });

        //item的点击
        contentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                handleItemClick(datas.get(position));
            }
        });

        looperPagerAdapter.setOnLooperPageItemClickListener(new LooperPagerAdapter.OnLooperPageItemClickListener() {
            @Override
            public void onLooperItemClick(HomePagerContent.DataBean bean) {
                handleItemClick(bean);
            }
        });
    }

    private void handleItemClick(IBaseInfo item) {
        //拿到TicketPresenterImpl去加载数据
        TicketUtil.toTicketPage(getContext(), item);
    }

    /**
     * 切换指示器
     *
     * @param position
     */
    private void updateLooperIndicator(int position) {
        for (int i = 0; i < looperPointContainer.getChildCount(); i++) {
            View childAt = looperPointContainer.getChildAt(i);
            if (position == i) {
                childAt.setBackgroundResource(R.drawable.shape_indicator_point_select);
            } else {
                childAt.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
        }
    }

    @Override
    protected void initView(View rootView) {
        //设置布局管理器
        mContentList.setLayoutManager(new LinearLayoutManager(getContext()));
        mContentList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = SizeUtils.dip2px(getContext(),1.5f);
                outRect.bottom = SizeUtils.dip2px(getContext(),1.5f);

            }
        });
        //创建适配器
        contentAdapter = new LinearItemContentAdapter(R.layout.item_linear_goods_content, datas, getContext());
        headerView = LayoutInflater.from(getContext()).inflate(R.layout.header_fragment_home_pager, null);
        looperPager = headerView.findViewById(R.id.looper_pager);
        looperPointContainer = headerView.findViewById(R.id.looper_point_container);
        currentCategoryTitleTv = headerView.findViewById(R.id.home_pager_title);
        contentAdapter.setHeaderView(headerView);
        //设置适配器
        mContentList.setAdapter(contentAdapter);

        //创建轮播图适配器
        looperPagerAdapter = new LooperPagerAdapter();
        //设置轮播图适配器
        looperPager.setAdapter(looperPagerAdapter);

        //设置Refresh相关属性
        twinklingRefreshLayout.setEnableRefresh(false);
        twinklingRefreshLayout.setEnableLoadmore(true);
    }

    @Override
    protected void loadData() {
        Bundle argument = getArguments();
        String title = argument.getString(KEY_HOME_PAGER_TITLE);
        materialid = argument.getInt(KEY_HOME_PAGER_MATERIAL_ID);
        //加载数据
        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.getContentByCategoryId(materialid);
        }
        if (currentCategoryTitleTv != null) {
            currentCategoryTitleTv.setText(title);
        }
    }

    @Override
    protected void initPresenter() {
        mCategoryPagerPresenter = PresenterManager.getInstance().getCategoryPagePresenter();
        mCategoryPagerPresenter.registerViewCallback(this);
    }

    @Override
    public void onContentLoaded(List<HomePagerContent.DataBean> data) {
        //数据列表加载到了
        setUpState(State.SUCCESS);
        datas.addAll(data);
    }

    @Override
    public int getCategoryId() {
        return materialid;
    }

    @Override
    public void onLoading() {
        setUpState(State.LOADING);
    }

    @Override
    public void onError() {
        //网络错误
        setUpState(State.ERROR);
    }

    @Override
    public void onEmpty() {
        setUpState(State.EMPTY);
    }

    @Override
    public void onLoaderMoreError() {
        ToastUtil.showToast("网络异常，请稍后重试");
        finishLoadMore();
    }

    @Override
    public void onLoaderMoreEmpty() {
        ToastUtil.showToast("没有更多商品");
        finishLoadMore();
    }

    @Override
    public void onLoaderMoreLoaded(List<HomePagerContent.DataBean> data) {
        //添加到适配器数据的底部
        contentAdapter.addListData(data);
        finishLoadMore();
    }

    private void finishLoadMore() {
        if (twinklingRefreshLayout != null) {
            twinklingRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void onLooperListLoadedList(List<HomePagerContent.DataBean> data) {
        looperPagerAdapter.setData(data);
        //设置到中间点
        int dx = (Integer.MAX_VALUE / 2) % data.size();
        int targetCenterPosition = (Integer.MAX_VALUE / 2) - dx;
        looperPager.setCurrentItem(targetCenterPosition);
        //添加点
        looperPointContainer.removeAllViews();
        for (int i = 0; i < data.size(); i++) {
            View point = new View(getContext());
            int size = SizeUtils.dip2px(getContext(), 8);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(size, size);
            layoutParams.leftMargin = SizeUtils.dip2px(getContext(), 5);
            layoutParams.rightMargin = SizeUtils.dip2px(getContext(), 5);
            point.setLayoutParams(layoutParams);
            if (i == 0) {
                point.setBackgroundResource(R.drawable.shape_indicator_point_select);
            } else {
                point.setBackgroundResource(R.drawable.shape_indicator_point_normal);
            }
            looperPointContainer.addView(point);
        }
    }

    @Override
    protected void release() {
        if (mCategoryPagerPresenter != null) {
            mCategoryPagerPresenter.unregisterViewCallback(this);
        }
    }
}
